package com.udp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * 一个UDP发送端，它向指定的服务器IP和端口发送用户输入的消息，
 * 并接收服务器返回的回声。
 */
public class UDPSender {

    public static void main(String[] args) {
        final String RECEIVER_IP = "127.0.0.1"; // 接收端的IP地址
        final int RECEIVER_PORT = 9876;        // 接收端的端口号
        final int BUFFER_SIZE = 1024;

        // DatagramSocket可以不指定端口，系统会自动分配一个可用端口
        try (DatagramSocket socket = new DatagramSocket();
             BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in))) {

            System.out.println("✅ UDP发送端已启动。");
            System.out.println("💡 输入消息并按回车发送，输入 'bye' 退出。");

            // 获取接收端的InetAddress对象
            InetAddress receiverAddress = InetAddress.getByName(RECEIVER_IP);

            String userInput;
            while ((userInput = consoleReader.readLine()) != null) {
                // 1. 准备要发送的数据
                byte[] sendData = userInput.getBytes("UTF-8");

                // 2. 创建要发送的数据报，需要指定数据、长度、目标IP和目标端口
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receiverAddress, RECEIVER_PORT);

                // 3. 发送数据报
                socket.send(sendPacket);
                System.out.println("➡️ 已发送消息: " + userInput);

                // 如果发送的是 "bye"，则不再等待回声，直接退出
                if ("bye".equalsIgnoreCase(userInput.trim())) {
                    break;
                }

                // 4. 准备接收回声数据
                byte[] buffer = new byte[BUFFER_SIZE];
                DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);

                // 5. 等待并接收回声
                socket.receive(receivePacket);

                // 6. 解析并打印回声
                String echoMessage = new String(receivePacket.getData(), 0, receivePacket.getLength(), "UTF-8");
                System.out.println("⬅️ 收到回声: " + echoMessage);
            }

        } catch (IOException e) {
            System.err.println("错误: " + e.getMessage());
        } finally {
            System.out.println("⏹️ UDP发送端已关闭。");
        }
    }
}
